<template>
  <div class="employee-role-container">
    <!-- 搜索条件卡片 -->
    <a-card class="search-card" :bordered="false">
      <a-form :model="searchForm" class="search-form">
        <div class="search-row">
          <a-form-item label="员工" class="search-item">
            <a-select
              v-model:value="searchForm.employeeId"
              placeholder="请选择员工"
              allow-clear
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="employee in employeeList"
                :key="employee.id"
                :value="employee.id"
              >
                {{ employee.name }}（{{ employee.account }}）
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="角色" class="search-item">
            <a-select
              v-model:value="searchForm.roleId"
              placeholder="请选择角色"
              allow-clear
              show-search
              :filter-option="filterOption"
            >
              <a-select-option
                v-for="role in roleList"
                :key="role.id"
                :value="role.id"
              >
                {{ role.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="" class="search-item search-buttons">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                查询
              </a-button>
              <a-button @click="resetSearch">
                <template #icon><reload-outlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </div>
      </a-form>
    </a-card>

    <!-- 员工角色关系列表卡片 -->
    <a-card class="employee-role-card" :bordered="false">
      <template #title>
        <div class="card-header">
          <a-space>
            <a-button type="primary" @click="handleAdd" class="add-button">
              <template #icon><plus-outlined /></template>
              添加关系
            </a-button>
            <a-button type="primary" @click="handleBatchAssign" class="assign-button">
              <template #icon><team-outlined /></template>
              批量分配
            </a-button>
          </a-space>
        </div>
      </template>

      <a-table
        :dataSource="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="false"
        rowKey="id"
        bordered
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <div class="action-btns">
              <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          :pageSizeOptions="['10', '20', '50', '100']"
          showSizeChanger
          showQuickJumper
          :showTotal="total => `共 ${total} 条`"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
          :locale="{ items_per_page: '条/页', jump_to: '跳至', page: '页' }"
        />
      </div>
    </a-card>

    <!-- 添加员工角色关系组件 -->
    <add-employee-role
      :visible="addVisible"
      @update:visible="addVisible = $event"
      @success="fetchEmployeeRoles"
    />

    <!-- 批量分配角色组件 -->
    <batch-assign-roles
      :visible="batchAssignVisible"
      @update:visible="batchAssignVisible = $event"
      @success="fetchEmployeeRoles"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  TeamOutlined
} from '@ant-design/icons-vue'
import {
  getEmployeeRoleList,
  deleteEmployeeRole
} from '@/api/employeeRole'
import { getEmployeeList } from '@/api/employee'
import { getRoleList } from '@/api/role'
import AddEmployeeRole from './components/AddEmployeeRole.vue'
import BatchAssignRoles from './components/BatchAssignRoles.vue'

// 表格列定义
const columns = [
  { title: '关系ID', dataIndex: 'id', key: 'id', width: 80, align: 'center'},
  { title: '员工ID', dataIndex: 'employeeId', key: 'employeeId', width: 80, align: 'center' },
  { title: '员工姓名', dataIndex: 'employeeName', key: 'employeeName', width: 120, align: 'center' },
  { title: '角色ID', dataIndex: 'roleId', key: 'roleId', width: 80, align: 'center' },
  { title: '角色名称', dataIndex: 'roleName', key: 'roleName', width: 120, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180, align: 'center' },
  { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', width: 180, align: 'center' },
  { title: '操作', key: 'action', fixed: 'right', width: 100, align: 'center' }
]

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 员工和角色列表
const employeeList = ref([])
const roleList = ref([])

// 搜索表单
const searchForm = reactive({
  employeeId: undefined,
  roleId: undefined
})

// 对话框控制
const addVisible = ref(false)
const batchAssignVisible = ref(false)

// 页面加载时获取数据
onMounted(() => {
  fetchEmployeeRoles()
  fetchEmployees()
  fetchRoles()
})

// 获取员工角色关系列表
const fetchEmployeeRoles = async () => {
  loading.value = true
  try {
    const res = await getEmployeeRoleList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      employeeId: searchForm.employeeId,
      roleId: searchForm.roleId
    })
    tableData.value = res.data.items
    total.value = res.data.totalRow
  } catch (error) {
    message.error('获取员工角色关系列表失败')
  } finally {
    loading.value = false
  }
}

// 获取员工列表
const fetchEmployees = async () => {
  try {
    const res = await getEmployeeList({ pageNum: 1, pageSize: 1000 })
    employeeList.value = res.data.items
  } catch (error) {
    message.error('获取员工列表失败')
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getRoleList({ pageNum: 1, pageSize: 1000 })
    roleList.value = res.data.items
  } catch (error) {
    message.error('获取角色列表失败')
  }
}

// 搜索过滤函数
const filterOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchEmployeeRoles()
}

// 重置搜索
const resetSearch = () => {
  searchForm.employeeId = undefined
  searchForm.roleId = undefined
  handleSearch()
}

// 页码变化
const handlePageChange = () => {
  fetchEmployeeRoles()
}

// 页大小变化
const handleSizeChange = () => {
  currentPage.value = 1
  fetchEmployeeRoles()
}

// 添加员工角色关系
const handleAdd = () => {
  addVisible.value = true
}

// 批量分配角色
const handleBatchAssign = () => {
  batchAssignVisible.value = true
}

// 删除员工角色关系
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除员工【${record.employeeName}】与角色【${record.roleName}】的关系吗？`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteEmployeeRole(record.id)
        message.success('删除成功')
        fetchEmployeeRoles()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.employee-role-container {
  padding: 16px;
  
  .search-card {
    margin-bottom: 16px;

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .search-form {
      .search-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;
        
        .search-item {
          flex: 0 0 calc(33.333% - 11px);
          margin-bottom: 0;
          
          :deep(.ant-form-item-label) {
            width: 80px;
            text-align: right;
          }
          
          :deep(.ant-form-item-control) {
            flex: 1;
          }
        }
      }
      
      .search-buttons {
        :deep(.ant-form-item-label) {
          display: none;
        }
        
        :deep(.ant-space) {
          display: flex;
          justify-content: flex-start;
        }
      }
    }
  }
  
  .employee-role-card {
    :deep(.ant-card-head) {
      min-height: 48px;
      padding: 0 16px;
      
      .ant-card-head-title {
        padding: 12px 0;
      }
    }
    :deep(.ant-card-body) {
      padding: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }
  
    
    :deep(.ant-table-thead > tr > th) {
      text-align: center;
    }
  }
  
  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .action-btns {
    display: flex;
    gap: 4px;
    justify-content: center;
  }
}
</style>